<?php

declare(strict_types=1);

namespace app\middleware;

use think\facade\Db;

class UserPermissionCheck
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $no_nedd_auth_url = [
            'api/auth/getInfo',
            'api/auth/getRouters',
            'member/user/profile',
            'member/user/updateProfile',
            'member/user/updatePwd',
        ];
        $request_route_rule = $request->rule()->getRule();
        $perm = str_replace('/', ':', $request_route_rule);

        $user_id = $request->create_by;
        $user_type = $request->user_type;

        $user = Db::table('member_user')->where('id', $user_id)->find();
        //超级管理员直接跳过
        if ($user_type == 'admin') {
            return $next($request);
        }
        // if ($user['parent_id'] == 0 || in_array($request_route_rule, $no_nedd_auth_url)) {
        //     return $next($request);
        // }

        if (!$user) {
            return error('用户不存在');
        }
        if ($user['parent_id'] == 0) {
            $perms_menus = Db::table('member_menu')->where('menu_type', 'F')->column('perms');
        } else {
            //获取角色菜单
            $user_menus_id = DB::table('member_user_menu')->whereIn('user_id', $user_id)->column('menu_id');
            //获取菜单
            $perms_menus = Db::table('member_menu')->whereIn('id', $user_menus_id)->where('menu_type', 'F')->column('perms');
        }

        if (!in_array($perm, $perms_menus)) {
            return error('无权限2');
        }

        return $next($request);
    }
}
